﻿/*
*类名：ShortVideoMessageDeal
*归属：QinMing.Weixin.MessageHandlerShortVideo命名空间
*用途：处理微信用户发给公众号的小视频消息，并给予微信用户处理结果通知，通过微信服务器转发给微信用户
*作者：乱世刀疤
*日期：2020.05.02
*/

using System;
using System.Web;
using System.Xml;
using System.Text;
using System.IO;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using QinMing.Config;
using QinMing.Weixin.ReturnContent;
using QinMing.WeixinContainer;
using QinMing.Tools;

namespace QinMing.Weixin.MessageHandlerShortVideo
{
	//小视频消息处理
    public class ShortVideoMessageDeal :System.Web.UI.Page
    {

		public string DealResult(string weixinXML)
        {
            string content = DealShortVideo(weixinXML);  
            return content;
        }
        
        public string DealShortVideo(string weixinXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);
            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;   //关注用户的加密后openid
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;       //公众微信号原始ID
            string MsgType = xn.SelectSingleNode("//MsgType").InnerText;
			string MediaId = xn.SelectSingleNode("//MediaId").InnerText.ToString().Trim();
			string ThumbMediaId = xn.SelectSingleNode("//ThumbMediaId").InnerText.ToString().Trim();
			string MsgId = xn.SelectSingleNode("//MsgId").InnerText;
            string strresponse = "";

			//保存用户发来的小视频信息
			SaveShortVideo(FromUserName, ToUserName, MediaId, ThumbMediaId, MsgId);
			
			//保存用户发来的小视频文件，保存文件之前最好先给微信服务器一个响应，防止视频文件过大保存时间过长，strresponse回复时微信服务器报错
			string ResultVideoUrl = DownloadFileByMediaId(FromUserName, MediaId, ThumbMediaId); 

			//引用QinMing.Weixin.ReturnContent命名空间下的ReturnMsg类来生成固定格式的回应消息
			ReturnMsg rm = new ReturnMsg();
			strresponse = rm.ReturnText(FromUserName, ToUserName, "<a href='" + ResultVideoUrl + "'>点击这里查看您刚发的视频</a>");
			
			//告知客服人员有新的留言，或者启动客服消息管理工单流程
			QinMing.WeixinTemplateMessage.SendTemplateMessage.SendRemindMsg("管理员openid", "客户发送小视频", "");  
			
			return strresponse; 
        }
		
		//把用户发来的小视频信息保存到数据表表中
		public void SaveShortVideo(string FromUserName, string ToUserName, string MediaId, string ThumbMediaId, string MsgId)
		{
            SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
			
			cmd.CommandText = "insert into weixin_recv_msg (msg_type,msg_id,open_id,gh_id,recv_time,media_id,video_thumb_media_id) values("
			    + "'shortvideo','" + MsgId + "','" + FromUserName + "','" + ToUserName + "',getdate(),'" + MediaId + "','" + ThumbMediaId + "')";
            cmd.ExecuteScalar();
			
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
		}
		
		//使用MediaId加基础access_token从微信服务器下载视频文件
		public string DownloadFileByMediaId(string FromUserName, string MediaId, string ThumbMediaId)
		{
			//获取普通基础access_token
			QinMingWeixinContainer wc = new QinMingWeixinContainer();
			string access_token = wc.GetAccessToken();
			
			string imgurl = "";
			string TmpDir = "E:\\web目录\\Video\\Upload\\";
			string TmpFileName = FromUserName + DateTime.Now.Ticks.ToString() + ".";
			string TmpExtName = "";
			
			string strUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + MediaId; 
			var q = HttpWebRequest.Create(strUrl).GetResponse();
			var s = q.GetResponseStream();
			var b = new BinaryReader(s);
			QinMingTools.WriteLog("Headers", q.Headers.ToString());   //微信服务器返回的Headers中包含文件名以及后缀名，可以使用正则表达式取后缀名
			QinMingTools.WriteLog("Headers里面的内容之一", q.Headers["Content-disposition"]);
			string tmpext = q.Headers["Content-disposition"];
			TmpExtName = tmpext.Substring(tmpext.LastIndexOf(".") + 1, (tmpext.Length - tmpext.LastIndexOf(".") - 2));    //这里用取字符串子串方式取出文件后缀名
			var file = TmpDir + TmpFileName + TmpExtName;
			FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
			fs.Write(b.ReadBytes((int)q.ContentLength), 0, (int)q.ContentLength);
			fs.Close();
			b.Close();
			s.Close();
			
			return "http://www.yourweb.com/Video/Upload/" + TmpFileName + TmpExtName;
			
			//此处可以添加用户发送小视频保存到数据库记录处理，用于对粉丝进行行为分析，以及使用客户发送的小视频文件
		}
    }
}